const base = require("./../base");
const Code = require("./../../../../../lib/wxa/code.class");
const lodash = require("lodash");
const moment = require("moment");

const wxaDomain = {
    requestdomain: [
        "https://api.doodooke.com",
        "https://api.doodooke.qingful.com"
    ],
    wsrequestdomain: [
        "wss://api.doodooke.com",
        "wss://api.doodooke.qingful.com"
    ],
    uploaddomain: [
        "https://api.doodooke.com",
        "https://api.doodooke.qingful.com"
    ],
    downloaddomain: [
        "https://api.doodooke.com",
        "https://api.doodooke.qingful.com"
    ]
};

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
    }

    async _before() {
        this.code = new Code(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );
        try {
            this.state.wxa = await this.checkWxaAuthorizerAccessToken(
                this.state.wxa
            );
        } catch (err) {
            this.status = 500;
            throw err;
        }
    }

    /**
     *
     * @api {post} /home/wxa/code/submitAudit 小程序提交审核
     * @apiDescription 小程序提交审核
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} user_desc 用户描述
     *
     * @apiSampleRequest /home/wxa/code/submitAudit
     */
    async submitAudit() {
        const { user_desc } = this.query;
        const { audit_items } = this.post;
        const templateWxaId = this.state.app.template_wxa_id;
        const templateWxa = await this.model("template_wxa")
            .query(qb => {
                qb.where("id", templateWxaId);
            })
            .fetch();

        // 域名
        const modifyDomain = await this.code.modify_domain(
            this.state.wxa.authorizer_access_token,
            "set",
            wxaDomain
        );
        if (modifyDomain.errmsg === "ok") {
            await this.model("wxa")
                .forge({
                    id: this.state.wxa.id,
                    request_domain: modifyDomain.requestdomain.join(),
                    wsrequest_domain: modifyDomain.wsrequestdomain.join(),
                    upload_domain: modifyDomain.uploaddomain.join(),
                    download_domain: modifyDomain.downloaddomain.join()
                })
                .save();
        } else {
            this.fail(this.wxaErr(modifyDomain));
            return;
        }

        // 网页
        try {
            await this.code.set_webview_domain(
                this.state.wxa.authorizer_access_token
            );
        } catch (err) {}

        const wxaAudit = {
            template_wxa_id: templateWxaId,
            templateid: templateWxa.templateid,
            ext_json: JSON.stringify(
                lodash.merge(
                    {
                        window: {
                            navigationBarTitleText: this.state.wxa.nick_name
                        }
                    },
                    JSON.parse(templateWxa.ext_json || "{}"),
                    {
                        ext: Object.assign(this.query, {
                            envVersion: "release",
                            appid: this.state.wxa.authorizer_appid
                        })
                    }
                )
            ),
            user_version: moment().format("YYYYMMDD"),
            user_desc: user_desc || "小程序平台"
        };

        console.log("提交审核二维码");
        console.log(wxaAudit);

        const commit = await this.code.commit(
            this.state.wxa.authorizer_access_token,
            wxaAudit.templateid,
            wxaAudit.ext_json,
            wxaAudit.user_version,
            wxaAudit.user_desc
        );
        if (commit.errmsg !== "ok") {
            this.fail(this.wxaErr(commit));
            return;
        }

        const audit = await this.code.submit_audit(
            this.state.wxa.authorizer_access_token,
            audit_items
        );
        if (audit.errmsg === "ok") {
            const wxaAuditData = await this.model("wxa_audit")
                .query({
                    where: {
                        wxa_id: this.state.wxa.id
                    }
                })
                .fetch();
            const _wxaAuditData = {
                wxa_id: this.state.wxa.id,
                template_wxa_id: wxaAudit.template_wxa_id,
                templateid: wxaAudit.templateid,
                auditid: audit.auditid,
                audit_item: JSON.stringify(audit_items),
                ext_json: wxaAudit.ext_json,
                user_version: wxaAudit.user_version,
                user_desc: wxaAudit.user_desc,
                release: 0
            };
            if (wxaAuditData) {
                await this.model("wxa_audit")
                    .forge(
                        Object.assign(_wxaAuditData, {
                            id: wxaAuditData.id
                        })
                    )
                    .save();
            } else {
                await this.model("wxa_audit")
                    .forge(_wxaAuditData)
                    .save();
            }

            this.success(audit);
        } else {
            this.fail(this.wxaErr(audit));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/getWxaQrcode 获取小程序码
     * @apiDescription 获取小程序码
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} scene 场景值
     * @apiParam {String} page 小程序跳转链接
     *
     * @apiSampleRequest /home/wxa/code/getWxaQrcode
     */
    async getWxaQrcode() {
        const { scene = "welcome", page } = this.query;
        this.ctx.set(
            "Content-disposition",
            `attachment; filename=${this.state.wxa.user_name}.jpg`
        );

        this.body = this.code.getWxaQrcodeUnlimit(
            this.state.wxa.authorizer_access_token,
            scene,
            page
        );
    }

    /**
     *
     * @api {get} /home/wxa/code/getExpQrcode 获取小程序体验二维码
     * @apiDescription 获取小程序体验二维码
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} user_desc 用户描述
     *
     * @apiSampleRequest /home/wxa/code/getExpQrcode
     */
    async getExpQrcode() {
        const { user_desc, path } = this.query;
        const templateWxaId = this.state.app.template_wxa_id;
        const templateWxa = await this.model("template_wxa")
            .query(qb => {
                qb.where("id", templateWxaId);
            })
            .fetch();

        // 域名
        const modifyDomain = await this.code.modify_domain(
            this.state.wxa.authorizer_access_token,
            "set",
            wxaDomain
        );
        if (modifyDomain.errmsg === "ok") {
            await this.model("wxa")
                .forge({
                    id: this.state.wxa.id,
                    request_domain: modifyDomain.requestdomain.join(),
                    wsrequest_domain: modifyDomain.wsrequestdomain.join(),
                    upload_domain: modifyDomain.uploaddomain.join(),
                    download_domain: modifyDomain.downloaddomain.join()
                })
                .save();
        } else {
            this.fail(this.wxaErr(modifyDomain));
            return;
        }

        // 网页
        try {
            await this.code.set_webview_domain(
                this.state.wxa.authorizer_access_token
            );
        } catch (err) {}

        const wxaAudit = {
            template_wxa_id: templateWxaId,
            templateid: templateWxa.templateid,
            ext_json: JSON.stringify(
                lodash.merge(
                    {
                        window: {
                            navigationBarTitleText: this.state.wxa.nick_name
                        }
                    },
                    JSON.parse(templateWxa.ext_json || "{}"),
                    {
                        ext: Object.assign(this.query, {
                            envVersion: "trial",
                            appid: this.state.wxa.authorizer_appid
                        })
                    }
                )
            ),
            user_version: moment().format("YYYYMMDD"),
            user_desc: user_desc || "小程序平台"
        };

        console.log("体验二维码");
        console.log(wxaAudit);

        const commit = await this.code.commit(
            this.state.wxa.authorizer_access_token,
            wxaAudit.templateid,
            wxaAudit.ext_json,
            wxaAudit.user_version,
            wxaAudit.user_desc
        );
        if (!commit.errmsg === "ok") {
            this.fail(this.wxaErr(commit));
            return;
        }

        this.ctx.set(
            "Content-disposition",
            `attachment; filename=${this.state.wxa.user_name}.jpg`
        );
        this.body = this.code.get_exp_qrcode(
            this.state.wxa.authorizer_access_token,
            path
        );
    }

    /**
     *
     * @api {get} /home/wxa/code/category 获取授权小程序帐号的可选类目
     * @apiDescription 获取授权小程序帐号的可选类目
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/wxa/code/category
     */
    async category() {
        const category = await this.code.get_category(
            this.state.wxa.authorizer_access_token
        );
        if (category.errmsg === "ok") {
            this.success(category);
        } else {
            this.fail(this.wxaErr(category));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/latestAudit 获取小程序最近的审核信息 - 数据库
     * @apiDescription 获取小程序最近的审核信息
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/wxa/code/latestAudit
     */
    async latestAudit() {
        const latestAuditstatus = await this.code.get_latest_auditstatus(
            this.state.wxa.authorizer_access_token
        );
        if (latestAuditstatus.errmsg === "ok") {
            const auditid = latestAuditstatus.auditid;
            const wxaAudit = await this.model("wxa_audit")
                .query({ where: { auditid: auditid } })
                .fetch();
            this.success(Object.assign(wxaAudit || {}, latestAuditstatus));
        } else {
            this.success(this.wxaErr(latestAuditstatus));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/latestAuditstatus 获取小程序最近的审核信息 - 微信
     * @apiDescription 获取小程序最近的审核信息
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/wxa/code/latestAuditstatus
     */
    async latestAuditstatus() {
        const latestAuditstatus = await this.code.get_latest_auditstatus(
            this.state.wxa.authorizer_access_token
        );

        if (latestAuditstatus.errmsg === "ok") {
            this.success(latestAuditstatus);
        } else {
            this.success(this.wxaErr(latestAuditstatus));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/release 发布已通过审核的小程序
     * @apiDescription 发布已通过审核的小程序
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/wxa/code/release
     */
    async release() {
        const release = await this.code.release(
            this.state.wxa.authorizer_access_token
        );
        if (release.errmsg === "ok") {
            const wxaAudit = await this.model("wxa_audit")
                .query({ where: { wxa_id: this.state.wxa.id } })
                .fetch();
            if (wxaAudit) {
                await this.model("wxa_audit")
                    .forge({
                        id: wxaAudit.id,
                        release: 1
                    })
                    .save();
            }

            this.success(release);
        } else {
            this.fail(this.wxaErr(release));
        }
    }

    async revertcoderelease() {
        const release = await this.code.revertcoderelease(
            this.state.wxa.authorizer_access_token
        );
        if (release.errmsg === "ok") {
            this.success(release);
        } else {
            this.fail(this.wxaErr(release));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/undoCodeAudit 撤销小程序审核
     * @apiDescription 撤销小程序审核
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/wxa/code/undoCodeAudit
     */
    async undoCodeAudit() {
        const audit = await this.code.undocodeaudit(
            this.state.wxa.authorizer_access_token
        );
        if (audit.errmsg === "ok") {
            this.success(audit);
        } else {
            this.fail(this.wxaErr(audit));
        }
    }

    /**
     *
     * @api {get} /home/wxa/code/changeVisitstatus 修改小程序线上代码的可见状态
     * @apiDescription 修改小程序线上代码的可见状态
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} action 小程序状态
     *
     * @apiSampleRequest /home/wxa/code/changeVisitstatus
     */
    async changeVisitstatus() {
        const { action = "open" } = this.query;
        const visitstatus = await this.code.change_visitstatus(
            this.state.wxa.authorizer_access_token,
            action
        );
        if (visitstatus.errmsg === "ok") {
            this.success(visitstatus);
        } else {
            this.fail(this.wxaErr(visitstatus));
        }
    }
};
